<template>
  <div class="app">
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>章节管理</el-breadcrumb-item>
      <el-breadcrumb-item>上架章节</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <div>
      <el-form
        :model="chapterFrom"
        :rules="rules"
        ref="ruleForm"
        label-width="130px"
        class="demo-ruleForm"
        v-loading="loading"
      >
        <el-form-item label="章节名称" prop="chapterName">
          <el-input v-model="chapterFrom.chapterName"></el-input>
        </el-form-item>
        <el-form-item label="上架时间" prop="chapterLaunchTime">
          <el-date-picker
            v-model="chapterFrom.chapterLaunchTime"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item ref="sel" label="书籍名称" prop="chapterBookId">
          <el-select
            v-model="chapterFrom.chapterBookId"
            filterable
            placeholder="请选择"
            @change="chan"
          >
            <el-option
              v-for="item in bookList"
              :key="item._id"
              :label="item.bookName"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前书籍最近章节">
          <el-dropdown
            v-loading="dropdownLoading"
            element-loading-spinner="el-icon-loading"
          >
            <el-button
              size="mini"
              :disabled="oldBookChapterList.length == 0"
              :style="oldBookChapterList.length == 0?'background-color:rgb(255,124,36,0.57) !important;border-color:rgb(255,124,36,0.3) !important;':''"
              type="primary"
            >
              划入查看<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item class="my-el-dropdown-item" v-if="oldBookChapterList.length == 0"
                >无内容</el-dropdown-item
              >
              <el-dropdown-item
              class="my-el-dropdown-item"
                :key="item._id"
                v-for="item in oldBookChapterList"
                >{{ item.number }} {{ item.chapterName }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
        <el-form-item label="章节文件">
          <el-upload
            class="upload-demo "
            action="#"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".txt"
            :http-request="uploadFile"
            :on-change="onChange"
            :before-upload="beforeUpload"
            :on-success="onSuccess"
          >
            <el-button size="small" class="my-el-button" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传txt文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="章节字数" prop="chapterNumber">
          <el-input disabled v-model="chapterFrom.chapterNumber"></el-input>
        </el-form-item>

        <el-form-item>
          <el-badge value="" class="item">
            <el-button :class="flagUpload=='primary'?'my-el-button':''" :type="flagUpload" @click="submitForm('ruleForm')"
              >添加章节</el-button
            >
            <el-button :class="flagUpload=='primary'?'my-el-button':''" :type="flagUpload" @click="chapterSorting('ruleForm')"
              >插入章节</el-button
            >
          </el-badge>
          <el-button class="my-el-button-default" @click="resetForm('ruleForm')">重置</el-button>
          <el-button type="success" @click="onLineEdit">在线编辑</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :title="selectBook.bookName + '书籍章节'"
      :visible.sync="dialogTableVisible"
    >
      <draggable
        :v-if="BookChapterSort.length > 0"
        v-model="BookChapterSort"
        @update="datadragEnd"
        :options="{ animation: 200 }"
      >
        <div
          :class="'drag-item ' + (item.newFlag || '')"
          v-for="(item, i) in BookChapterSort"
          :key="i"
        >
          <el-row>
            <el-col class="line" :span="6"
              >&nbsp;{{
                '第' + numForStr(i + 1) + '章节  ' + item.chapterName
              }}</el-col
            >
            <el-col :span="5">
              <el-button
                v-if="item.is_system != 1"
                type="text"
                size="mini"
                class="my-el-button-text"
                @click="deleCode(i, item)"
                >删除</el-button
              >
            </el-col>
          </el-row>
        </div>
      </draggable>
    </el-dialog>
  </div>
</template>
<script>
import {
  uploadImg,
  uploadImgTrue,
  queryBookById,
  bookModify
} from '@/network/bookManager'
import {
  queryBookAll,
  addChapter,
  queryChapterLately,
  queryChapterCountByBookId,
  modifyChapterByBookId
} from '@/network/chapterManager'
import { timeStampFormatStr } from '@/util/dataTimeUtil'
export default {
  data() {
    return {
      // 添加书籍章节 对象
      chapterFrom: {
        _id: '',
        chapterBookId: '',
        chapterLaunchTime: '',
        chapterName: '',
        chapterNumber: 0,
        chapterContentUrl: '',
        chapterStatus: 1
      },
      rules: {
        // 表单检验
        chapterName: [
          { required: true, message: '请输入章节标题', trigger: 'blur' }
        ],
        chapterLaunchTime: [
          { required: true, message: '请选择上传时间', trigger: 'change' }
        ],
        chapterBookId: [
          { required: true, message: '请选择书籍', trigger: 'change' }
        ]
      },
      file: null, // 上传的文件
      fileList: [], // 上传的文件
      bookList: [], // 书籍数组
      flagUpload: 'primary',
      //
      oldBookChapterList: [],
      oldBookChapterCount: 0,
      BookChapterSort: [], // 拖拽排序数组
      selectBook: {}, // 下拉框选中的书籍对象
      dialogTableVisible: false, // 对话框 显示与隐藏
      dropdownLoading: false,
      chapterId: '', // 添加后的章节id
      bookName: '', // 书籍名称
      loading: false, // 表单加载
      user: {},
      role:{}
    }
  },
  methods: {
    // 提交按钮
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.file == null)
            return this.$message.warning('请选择需要上传的章节文件')
          if (this.chapterFrom.chapterContentUrl == '')
            return this.$message.warning('请先等待章节文件上传完成')
          if (this.flagUpload == 'warning') {
            this.$confirm('当前章节已被上传，是否继续上传?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                this.addChapterAndModify()
              })
              .catch(() => {
                return this.$message.info('已取消上传')
              })
          } else {
            this.addChapterAndModify()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 章节排序
    async chapterSorting(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.file == null)
            return this.$message.warning('请选择需要上传的章节文件')
          if (this.flagUpload != 'warning') {
            this.addChapterAndModify()
            this.sortChapter()
            return
          }
          this.$confirm('当前章节已被上传，是否继续上传?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              let res = await this.addChapterAndModify()
              console.info(res)
              // this.chapterFrom._id = res.data[0]
              this.sortChapter()
            })
            .catch(() => {
              return this.$message.info('已取消上传')
            })
        }
      })
    },
    // 重置表单方法
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.chapterFrom.chapterNumber = ''
      this.chapterFrom.chapterContentUrl = ''
      this.file = null
      this.fileList = []
      this.flagUpload = 'primary'
      this.oldBookChapterList = []
    },
    // 自定义上传方法
    async uploadFile() {
      if (this.chapterFrom.chapterBookId == '') {
        this.$message.warning('请先选择你要上传章节的书籍')
      }
      let file = this.file
      console.info(file.raw.type)

      console.info(this.file)
      const imgName = (
        `boxContent/${this.selectBook.bookName}/` +
        new Date().getTime() +
        '-' +
        file.name
      ).replace('.txt', '.json')

      let res = await uploadImg(imgName)
      console.info(res)
      // 将返回的地址 处理成代理地址
      let website = res.url.substring(0, res.url.indexOf('com') + 3)
      let trueUrl = res.url.replace(website, '/img')
      // 将数据封装成 formData
      const formData = new FormData()
      formData.append('Signature', res.authorization)
      formData.append('key', imgName)
      formData.append('x-cos-security-token', res.token)
      formData.append('x-cos-meta-fileid', res.cos_file_id)
      formData.append('file', file.raw)
      uploadImgTrue(trueUrl, formData) // 最后一步上传图片
      const fileUrl = `https://7a68-zhuma-mbnti-1302831863.tcb.qcloud.la/${imgName}`
      this.chapterFrom.chapterContentUrl = fileUrl // 将图片路径 存入表单对象中
      console.info(fileUrl)
    },
    // 文件移除时的 钩子
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.chapterFrom.chapterNumber = ''
      this.file = null
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file)
    },
    // 文件超出限制 钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 文件删除之间钩子
    beforeRemove(file) {
      console.info(file)

      // return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 文件改变钩子
    onChange(file, fileList) {
      if (this.chapterFrom.chapterBookId == '') {
        return false
      }
      this.file = file
      this.fileList = fileList
    },
    // 上传之前钩子
    beforeUpload(file) {
      if (file.size / 1204 > 500) {
        this.$message.warning('文件大小不能超过500kb')
        return false
      }
    },
    // 上传成功后的回调
    onSuccess(resp, file) {
      this.$message.success('文件上传成功')
      let reader = new FileReader()
      if (typeof FileReader === 'undefined') {
        this.$message({
          type: 'info',
          message: '您的浏览器不支持FileReader接口'
        })
        return
      }
      reader.readAsText(file.raw)
      reader.onload = e => {
        let res = e.target.result
        this.chapterFrom.chapterNumber = res.length
      }
      console.info(file)
    },
    // 查询 当前书籍 最近5个章节
    async chan(val) {
      this.dropdownLoading = true
      let obj = {}
      obj = this.bookList.find(item => {
        //遍历list的数据
        return item._id === val //筛选出匹配数据
      })
      console.info(obj)
      this.selectBook = obj
      let res = await queryChapterLately(
        this.chapterFrom.chapterBookId,
        5,
        'desc',
        1
      ) // 查询书籍的旧章节
      let resCount = await queryChapterCountByBookId(
        this.chapterFrom.chapterBookId
      )
      this.oldBookChapterCount = resCount.count + 1
      this.oldBookChapterList = []
      for (let rs in res.data) {
        let bookChapter = JSON.parse(res.data[rs])
        bookChapter['number'] = `第${this.numForStr(
          (this.oldBookChapterCount -= 1)
        )}章`
        this.oldBookChapterList.push(bookChapter)
      }
      this.dropdownLoading = false
      console.info(res)
    },
    // 在线编辑
    onLineEdit() {
      this.$router.push({
        path: '/onlineedit'
      })
    },
    // 添加章节 并修改图书信息
    async addChapterAndModify() {
      // this.chapterFrom.chapterName = `第${this.numForStr(resCount.count + 1)}章 `+this.chapterFrom.chapterName
      // 添加 章节
      this.loading = true
      let res = await addChapter(this.chapterFrom)
      console.info(res)
      if (res.errcode != 0) return this.$message.error('上传失败')
      this.flagUpload = 'warning'
      this.$message.success('上传成功，如需上传其他章节，请点击重置按钮并继续')
      let bookRes = await queryBookById(this.chapterFrom.chapterBookId)
      // 修改书籍的总字数 与最近修改时间
      if (bookRes.errcode == 0 && bookRes.data.length > 0) {
        let book = JSON.parse(bookRes.data[0])
        bookModify({
          _id: book._id,
          bookNumberOfWords:
            book.bookNumberOfWords + this.chapterFrom.chapterNumber,
          bookToUpdate: {
            date: timeStampFormatStr(+new Date())
          },
          bookGeneralSection: book.bookGeneralSection + 1
        })
      }
      this.loading = false
    },
    // 将 阿拉伯数字123 转换成 字符串数字一二三
    numForStr(n) {
      var cnum = [
        '零',
        '一',
        '二',
        '三',
        '四',
        '五',
        '六',
        '七',
        '八',
        '九',
        '十'
      ]
      var s = ''
      n = '' + n // 数字转为字符串
      for (var i = 0; i < n.length; i++) {
        s += cnum[parseInt(n.charAt(i))]
      }
      if (s.length == 2) {
        // 两位数的时候
        // 如果个位数是0的时候，令改成十
        if (s.charAt(1) == cnum[0]) {
          s = s.charAt(0) + cnum[10]
          // 如果是一十改成十
          if (s == cnum[1] + cnum[10]) {
            s = cnum[10]
          }
        } else if (s.charAt(0) == cnum[1]) {
          // 如果十位数是一的话改成十
          s = cnum[10] + s.charAt(1)
        }
      }
      return s
    },
    // 拖拽排序方法
    async datadragEnd(evt) {
      evt.preventDefault()
      console.log('拖动前的索引 :' + evt.oldIndex)
      console.log('拖动后的索引 :' + evt.newIndex)
      let newIndex = evt.newIndex
      // 遍历数组,将索引值赋值到对应的sort_order上面,完成排序
      let arr = this.BookChapterSort
      let newArr = await arr.map((item, i) => {
        return {
          sort_order: i,
          chapterName: item.chapterName,
          chapterLaunchTime: item.chapterLaunchTime,
          _id: item._id
        }
      })
      let afterChapter = newArr[newIndex + 1]
      let beforeChapter = newArr[newIndex - 1]
      let newChapterLaunchTime = ''
      // 当移到最末尾时
      if (afterChapter == undefined) {
        newChapterLaunchTime =
          new Date(beforeChapter.chapterLaunchTime).getTime() + 1000 * 60 * 5
      }
      // 当移到最首位时
      if (beforeChapter == undefined) {
        newChapterLaunchTime =
          new Date(afterChapter.chapterLaunchTime).getTime() - 1000 * 60 * 5
      }
      if (afterChapter != undefined && beforeChapter != undefined) {
        newChapterLaunchTime =
          (new Date(afterChapter.chapterLaunchTime).getTime() +
            new Date(beforeChapter.chapterLaunchTime).getTime()) /
          2
      }

      newArr[newIndex].chapterLaunchTime = timeStampFormatStr(
        newChapterLaunchTime
      )
      let res = await modifyChapterByBookId(newArr[newIndex]) // 修改
      console.info(res)
      this.$message.success('修改成功')
      console.info(newArr)
    },
    // 删除章节
    deleCode(index, item) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.BookChapterSort.splice(index, 1)
          item.chapterStatus = 0
          let res = await modifyChapterByBookId(item)
          console.info(res)
          console.info(item)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 排序并展示
    async sortChapter() {
      let res = await queryChapterLately(this.chapterFrom.chapterBookId, '','',1) // 查询书籍的旧章节
      this.BookChapterSort = []
      for (let rs in res.data) {
        let chapter = JSON.parse(res.data[rs])
        chapter.chapterLaunchTime = timeStampFormatStr(
          chapter.chapterLaunchTime.$date
        )
        if (rs == res.data.length - 1) {
          chapter.newFlag = 'newChapter'
        }
        this.BookChapterSort.push(chapter)
      }
      console.info(this.BookChapterSort)
      this.dialogTableVisible = true
    }
  },
  // vue 生命周期方法
  async mounted() {
    this.role = JSON.parse(sessionStorage.getItem('role'))
    this.user = JSON.parse(sessionStorage.getItem('user'))
    let res = await queryBookAll({ authorId:this.role.roleName=='超级管理员'?'':this.user._id, bookStatus: 1 })
    this.bookList = []
    for (let rs in res.data) {
      this.bookList.push(JSON.parse(res.data[rs]))
    }
    console.info(res)
    console.info(this.bookList)
  }
}
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #409eff;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-badge {
  margin-right: 40px;
}
.el-button--success {
  margin-left: 20px;
}
.newChapter {
  color: rgb(252, 71, 71);
}
</style>
